﻿using Idenmpotency;

namespace Microsoft.AspNetCore.Idenmpotency
{
    /// <summary>
    /// 幂等性处理中间件
    /// </summary>
    public class IdenmpotencyMidllerware
    {
        private readonly RequestDelegate _next;
        private readonly IApplicationBuilder _app;
        public IdenmpotencyMidllerware(IApplicationBuilder app, RequestDelegate next)
        {
            _next = next;
            this._app = app;
        }
        public async Task Invoke(HttpContext context)
        {
            var requestFactory = context.RequestServices.GetService<IAspIdenmpotencyRequestFactory>();
            var request=requestFactory.Create(context,this._next);
            if(request==null)
            {
                await this._next(context);
                return;
            }
            var instance = context.RequestServices.GetService<IIdenmpotencyChecker>();
            CancellationTokenSource source = new CancellationTokenSource();
            await instance.CheckAsync(request, source.Token);
        }
    }
}
